<template>
  <view class="wrap">
    <video
      class="videoPlayer"
      id="videoPlayer"
      :src="filePath"
      controls
      @ended="onEnded"
      @timeupdate="onTimeUpdate"
      @loadedmetadata="onLoadedmetadata"
      @play="onPlay"
      @pause="onPause"
      object-fit="scale-down"
      :title="mediaName"
    />
  </view>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'

import { getVideoUrlBySportId } from './video.api'
import { onLoad, onUnload } from '@dcloudio/uni-app'
let videoContent: any = null
const videoList = ref<any>([])
const filePath = ref<string>('')
const fileIndex = ref<number>(0)
const mediaName = ref<string>('')

let backAudioContext: any = null
const backAudioFile =
  'https://minio.meilianshuke.com/mlsk/path/sport/dubbing/20250120/音乐赠送动感_34921.mp3'

let audioFiles = [
  'https://minio.meilianshuke.com/mlsk/path/sport/dubbing/other_words/20250120/预备_36493.mp3',
  'https://minio.meilianshuke.com/mlsk/path/sport/dubbing/other_words/20250120/GO_36492.mp3'
]
let nextAudioFiles = [
  'https://minio.meilianshuke.com/mlsk/path/sport/dubbing/other_words/20250120/下一个动作_36493.mp3',
  'https://minio.meilianshuke.com/mlsk/path/sport/dubbing/other_words/20250120/预备_36493.mp3',
  'https://minio.meilianshuke.com/mlsk/path/sport/dubbing/other_words/20250120/GO_36492.mp3'
]
let startAudioContent: any = null
let currentAudioIndex = 0 // 当前音频索引
const options = reactive({
  source: '',
  list: []
})
onLoad(async (option: any) => {
  currentAudioIndex = 0
  console.log(option)
  options.source = option.source
  options.list = JSON.parse(decodeURIComponent(option.list))
  console.log(options.list)
  videoList.value = options.list

  initAudioPlayback()
  updateVideoSource()
})

const updateVideoSource = () => {
  filePath.value = videoList.value[fileIndex.value].fileUrl
  mediaName.value = videoList.value[fileIndex.value].mediaName

  // 更新导航栏标题
  uni.setNavigationBarTitle({
    title: mediaName.value
  })

  // 重新创建视频上下文
  videoContent = uni.createVideoContext('videoPlayer', this)
}

// 初始化音频播放
const initAudioPlayback = () => {
  if (!startAudioContent) {
    startAudioContent = uni.createInnerAudioContext()
    startAudioContent.autoplay = true
  }
  startAudioContent.src = audioFiles[currentAudioIndex]

  startAudioContent.onPlay(() => {
    // console.log(`播放音频 ${currentAudioIndex + 1}`)
  })

  startAudioContent.onEnded(() => {
    currentAudioIndex++
    if (currentAudioIndex < audioFiles.length) {
      startAudioContent.src = audioFiles[currentAudioIndex]
      startAudioContent.play()
    } else {
      startVideoPlayback()
    }
  })
}

const startVideoPlayback = () => {
  if (startAudioContent) {
    try {
      startAudioContent.stop()
      startAudioContent.offPlay()
      startAudioContent.offEnded()
    } catch (e) {
      //
    }
  }

  if (!backAudioContext) {
    backAudioContext = uni.createInnerAudioContext()
    backAudioContext.autoplay = true
    backAudioContext.src = backAudioFile
    backAudioContext.onPlay(() => {
      console.log('开始播放背景音乐')
    })

    backAudioContext.onPause(() => {
      console.log('暂停播放背景音乐')
    })
  }

  setTimeout(() => {
    videoContent.play()
  }, 150)
}

const onEnded = () => {
  if (fileIndex.value < videoList.value.length - 1) {
    fileIndex.value++

    // audioFiles = nextAudioFiles

    setTimeout(() => {
      currentAudioIndex = 0
      initAudioPlayback()
      updateVideoSource()
    }, 100)
  } else {
    videoContent.stop()
    if (backAudioContext) {
      try {
        backAudioContext.stop()
        backAudioContext.offPlay()
        backAudioContext.offEnded()
        backAudioContext.destroy()
      } catch (e) {
        // console.log(e)
      }
    }
    console.log('end')
    uni.navigateBack({
      delta: 1
    })
    // uni.redirectTo({
    //   url: `/module/src/pages/sports/sportsPlan/${options.source}`
    // })
  }
}

const onPlay = () => {
  if (!backAudioContext) {
    backAudioContext = uni.createInnerAudioContext()
    backAudioContext.autoplay = true
    backAudioContext.src = backAudioFile
    try {
      backAudioContext.play()
      backAudioContext.onPlay(() => {
        console.log('开始播放背景音乐')
      })

      backAudioContext.onPause(() => {
        console.log('暂停播放背景音乐')
      })
    } catch (e) {
      console.log(e)
    }
  }

  if (backAudioContext.paused) {
    try {
      backAudioContext.play()
    } catch (e) {
      console.log('播放背景音乐失败', e)
    }
  }
}

const onPause = () => {
  console.log('视频暂停')
  if (backAudioContext) {
    try {
      backAudioContext.pause()
    } catch (e) {
      // console.log(e)
    }
  }
}

const onTimeUpdate = (e: any) => {
  //
  // console.log('currentTime', Math.round(e.detail.currentTime * 100) / 100)
}
const onLoadedmetadata = () => {
  console.log('loaded', videoContent)
  videoContent.pause()
  // setTimeout(() => {
  //   videoContent.play()
  // }, 200)
}

onUnload(() => {
  if (startAudioContent) {
    try {
      startAudioContent.stop()
      startAudioContent.destroy()
    } catch (e) {
      console.log(e)
    }
  }
  if (backAudioContext) {
    try {
      backAudioContext.stop()
      backAudioContext.destroy()
      backAudioContext = null
    } catch (e) {
      console.log(e)
    }
  }
  videoContent = null
  currentAudioIndex = 0
})
</script>
<style lang="scss" scoped>
.wrap {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  align-items: center;
  background-color: rgba($color: #000000, $alpha: 0.8);

  .videoPlayer {
    width: 100%;
  }
}
</style>
